package com.zzlzd.drp.controller;

import com.alibaba.fastjson.JSONArray;
import com.qiniu.storage.model.DefaultPutRet;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.zzlzd.drp.config.BaseConfig;
import com.zzlzd.drp.config.RedisUtils;
import com.zzlzd.drp.config.ResponseInfo;
import com.zzlzd.drp.config.ResultGenerator;
import com.zzlzd.drp.domain.*;
import com.zzlzd.drp.util.QiniuUtils;
import com.zzlzd.drp.util.WxTempMsg;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private HttpServletRequest req;

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    ResultGenerator r;

    @Autowired
    AccountRepository accountRepository;

    @Autowired
    UserRepository userRepository;
    @Autowired
    GoodsRep goodsRep;
    @Autowired
    GoodsMenuRep goodsMenuRep;
    @Autowired
    LevelViewRep levelViewRep;
    @Autowired
    OrderViewRep orderViewRep;

    @Autowired
    BaseConfig baseConfig;
    @Autowired
    UserRepository userRep;

    @Autowired
    SwiperRep swiperRep;
    @Autowired
    AddressRep addressRep;
    @Autowired
    RelationRep relationRep;
    @Autowired
    MoneyLogRep moneyLogRep;
    @Autowired
    OrdersRep ordersRep;
    @Autowired
    OrderInfoRep orderInfoRep;
    @Autowired
    ArticleRep articleRep;
    @Autowired
    RankRep rankRep;
    @Autowired
    MenuRep menuRep;
    @Autowired
    DesignRep designRep;

    @PersistenceContext
    private EntityManager entityManager;

    private String adminusername = "";
    private String adminacccount = "";
    private Integer admintype = 0;

    /***
     * 获取登录信息
     * @return
     */
    private AccountDto getAccount() {
        HttpSession session =  req.getSession(false);
        if(session != null) {
            return (AccountDto) session.getAttribute("LOGIN");
        }else {
            return null;
        }
    }

    /***
     * 上传文件
     * @param img
     * @return
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/uploadImg")
    public ResponseInfo uploadHead(@RequestPart("img") MultipartFile img) throws IOException {
        String key = "Image_"+new Date().getTime() + ".png";
        QiniuUtils qiniuUtils = new QiniuUtils(baseConfig);
        DefaultPutRet resout = qiniuUtils.uploadFile(1,key,img.getInputStream());
        if(resout!=null){
            return r.sd(baseConfig.getUrl()+key);
        }else{
            return r.f("上传失败");
        }
    }

    public String toData(Date date){
        SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fffsd=sd.format(date);
        return fffsd;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }



    /***
     * 个人信息
     * @param model
     * @return
     */
    @GetMapping("/userinfo")
    public String userinfo(Model model) {
        AccountDto admin = getAccount();
        if(admin==null){
            return "/admin/auth_login";
        }
        model.addAttribute("admin",admin);
        model.addAttribute("IsEditPwd",admin.getIsEditPwd());
        return "/shop/editpwd";
    }

    /***
     * 修改密码
     * @return
     */
    @ResponseBody
    @PostMapping("/userinfo")
    public ResponseInfo userinfo(String oldpassword,String password) {
        HttpSession session =  req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.t();
        }

        if(!password.isEmpty()){
            if(!admin.getPassword().equals(oldpassword)){
                return r.f("修改失败：旧密码错误！");
            }else{
                if(oldpassword.equals(password)){
                    return r.f("新密码不能和旧密码相同");
                }
                admin.setPassword(password);
                admin.setIsEditPwd(0);
                accountRepository.save(admin);
                session.removeAttribute("LOGIN");
                return r.s();
            }
        }
        accountRepository.save(admin);
        session.setAttribute("LOGIN",admin);
        return r.s();
    }

    /**
     * date2比date1多的天数
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2)   //不同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0)    //闰年
                {
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else    //同一年
        {
            System.out.println("判断day2 - day1 : " + (day2-day1));
            return day2-day1;
        }
    }
    /***
     * 后台首页
     * @param model
     * @return
     */
    @GetMapping()
    public String index(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        Map<String,Integer> orders = ordersRep.orderChars();
        List<Map<String, Object>> people = userRep.peopleData();
        int count = 0;
        JSONArray time = new JSONArray();
        JSONArray num = new JSONArray();
        for(Map map:people){
            time.add(map.get("data"));
            num.add(map.get("count"));
            count = count+ Integer.parseInt(map.get("count").toString());
        }
        model.addAttribute("admin",admin);
        model.addAttribute("order",orders);
        model.addAttribute("time",time);
        model.addAttribute("num",num);
        model.addAttribute("count",count);
        return "/shop/index";
    }

    /***
     * 后台首页
     * @param model
     * @return
     */
    @GetMapping("/")
    public String index2(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        Map<String,Integer> orders = ordersRep.orderChars();
        List<Map<String, Object>> people = userRep.peopleData();
        int count = 0;
        JSONArray time = new JSONArray();
        JSONArray num = new JSONArray();
        for(Map map:people){
            time.add(map.get("data"));
            num.add(map.get("count"));
            count = count+ Integer.parseInt(map.get("count").toString());
        }
        model.addAttribute("admin",admin);
        model.addAttribute("order",orders);
        model.addAttribute("time",time);
        model.addAttribute("num",num);
        model.addAttribute("count",count);
        return "/shop/index";
    }



    /***
     * 会员列表
     * @param model
     * @return
     */
    @GetMapping("/userList")
    public String userList(Model model,Integer pageNum,String phone) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        LevelView levelView = new LevelView();
        levelView.setPhone(phone);
        Page<LevelView> userList = levelViewRep.findAll(Example.of(levelView),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",userList);
        return "/shop/user_list";
    }

    /***
     * 天使级别用户
     * @param model
     * @param pageNum
     * @param phone
     * @return
     */
    @GetMapping("/userListAngel")
    public String userListAngel(Model model,Integer pageNum,String phone) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        LevelView levelView = new LevelView();
        levelView.setLevels("天使");
        levelView.setPhone(phone);
        Page<LevelView> userList = levelViewRep.findAll(Example.of(levelView),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",userList);
        return "/shop/user_list_angel";
    }

    /***
     * 市代级别用户
     * @param model
     * @param pageNum
     * @param phone
     * @return
     */
    @GetMapping("/userListCity")
    public String userListCity(Model model,Integer pageNum,String phone) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        LevelView levelView = new LevelView();
        levelView.setLevels("市代");
        levelView.setPhone(phone);
        Page<LevelView> userList = levelViewRep.findAll(Example.of(levelView),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",userList);
        return "/shop/user_list_city";
    }
    /***
     * 省代级别用户
     * @param model
     * @param pageNum
     * @param phone
     * @return
     */
    @GetMapping("/userListProvince")
    public String userListProvince(Model model,Integer pageNum,String phone) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        LevelView levelView = new LevelView();
        levelView.setLevels("省代");
        levelView.setPhone(phone);
        Page<LevelView> userList = levelViewRep.findAll(Example.of(levelView),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",userList);
        return "/shop/user_list_province";
    }
    /***
     * 合伙人级别用户
     * @param model
     * @param pageNum
     * @param phone
     * @return
     */
    @GetMapping("/userListPartner")
    public String userListPartner(Model model,Integer pageNum,String phone) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        LevelView levelView = new LevelView();
        levelView.setLevels("分公司");
        levelView.setPhone(phone);
        Page<LevelView> userList = levelViewRep.findAll(Example.of(levelView),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",userList);
        return "/shop/user_list_partner";
    }
    /***
     * 订单列表
     * @param model
     * @param pageNum
     * @param id
     * @return
     */
    @GetMapping("/shopOrderList")
    public String shopOrderList(Model model,Integer pageNum,String id,Integer type) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        model.addAttribute("admin",admin);

        OrderView orderView = new OrderView();
        if(id!=null){
            orderView.setId(Integer.parseInt(id));
        }
        if(type==null){
            type = (int) session.getAttribute("oType");
        }
        if(type!=3){
            orderView.setState(type);
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）
        Page<OrderView> pageInfo = orderViewRep.findAll(Example.of(orderView),pageable);
        model.addAttribute("pageInfo",pageInfo);
        session.setAttribute("oType",type);
        return "/shop/shop_order_list";
    }

    /***
     * 购物车订单详情
     * @param model
     * @param pageNum
     * @param id
     * @return
     */
    @GetMapping("/shopOrderInfoList")
    public String shopOrderInfoList(Model model,Integer pageNum,Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        if(id==null){
            id = (int) session.getAttribute("oid");
        }
        model.addAttribute("admin",admin);

        OrderInfoDto orderInfoDto = new OrderInfoDto();
        orderInfoDto.setOid(id);
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）
        Page<OrderInfoDto> pageInfo = orderInfoRep.findAll(Example.of(orderInfoDto),pageable);
        model.addAttribute("pageInfo",pageInfo);
        session.setAttribute("oid",id);
        return "/shop/shop_order_info_list";
    }
    /***
     * 会员团队列表
     * @param model
     * @param id
     * @return
     */
    @GetMapping("/member")
    public String userList(Model model,String id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<Map<String,Object>> userList = userRep.findUserListById(id);
        model.addAttribute("userList",userList);
        return "/shop/member_list";
    }



    @GetMapping("/gift")
    public String userList(Model model,Integer pageNum,Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        if (pageNum == null){
            pageNum = 1;
        }
        if(id==null){
            id = (int) session.getAttribute("id");
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");  // 这里的"recordNo"是实体类的主键，记住一定要是实体类的属性，而不能是数据库的字段
        Pageable pageable = PageRequest.of(pageNum - 1, 10, sort); // （当前页， 每页记录数， 排序方式）

        MoneyLogDto moneyLogDto = new MoneyLogDto();
        moneyLogDto.setUserId(id);
        Page<MoneyLogDto> moneyLogDtos = moneyLogRep.findAll(Example.of(moneyLogDto),pageable);
        model.addAttribute("admin",admin);
        model.addAttribute("userList",moneyLogDtos);
        session.setAttribute("id",id);
        return "/shop/user_gift";
    }

    /***
     * 余额充值
     * @return
     */
    @ResponseBody
    @PostMapping("/pay")
    public ResponseInfo pay(Integer id,String money,String explain){
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f();
        }
        try {
            Double m = Double.valueOf(money);
            UserDto user = userRep.findUserById(id);
            if(user==null){
                return r.f("会员信息错误");
            }
            if(user.getPhone()==null){
                return r.f("请会员先绑定手机号");
            }
            user.setMoney(user.getMoney()+m);
            userRep.save(user);



            if(user.getOpenid()!=null&&m>0d){
                JSONObject data = new JSONObject();
                JSONObject name1 = new JSONObject();
                name1.put("value","+"+m);
                data.put("character_string2",name1);

                JSONObject thing3 = new JSONObject();
                thing3.put("value",user.getMoney().intValue());
                data.put("number3",thing3);

                JSONObject time4 = new JSONObject();
                time4.put("value",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                data.put("date4",time4);


                JSONObject date4 = new JSONObject();
                date4.put("value","系统充值");
                data.put("thing5",date4);
                WxTempMsg.sendMsg(user.getOpenid(),"/pages/me/gift/gift",data,"FcH8-N5I11v3aoWL1uBw4Ve7prezDHioZmpTLLW9O4c");
            }


            MoneyLogDto moneyLogDto = new MoneyLogDto();
            moneyLogDto.setUserId(0);
            moneyLogDto.setMoney(m);
            moneyLogDto.setType(2);//划拨
            moneyLogDto.setRemarks("向 会员编号："+user.getId()+" 会员名称："+user.getName()+" 会员手机号："+user.getPhone()+" 划拨 "+m);
            moneyLogDto.setCreatTime(new Date());

            moneyLogDto.setSid(user.getId());
            moneyLogDto.setPlain(explain);
            moneyLogRep.save(moneyLogDto);


            MoneyLogDto pMoney = new MoneyLogDto();
            pMoney.setUserId(user.getId());
            pMoney.setMoney(m);
            pMoney.setType(0);//收入
            pMoney.setRemarks("收到 系统 划拨 "+m);
            pMoney.setCreatTime(new Date());
            pMoney.setSid(0);
            pMoney.setPlain(explain);
            moneyLogRep.save(pMoney);

            return r.s();
        }catch (Exception e){
            return r.f("请输入正确的积分");
        }
    }

    /***
     * 升级
     * @param userDto
     */
    public void UpLevel(UserDto userDto){
        Map<String,Object> one = relationRep.findUpById(userDto.getId());
        if(!one.isEmpty()) {
            /*****
             * 在此处理等级晋升
             */
            Integer id = Integer.parseInt(one.get("id").toString());
            Integer level = Integer.parseInt(one.get("level").toString());

            //上级增加推荐天使
            RankDto levelLog = rankRep.getOneByUid(id);
            levelLog.setDl(levelLog.getDl()+1);
            rankRep.save(levelLog);


            //如果上级为天使 且新增了三个天使 则上级升级市代
            if(levelLog.getDl()==3&&level==1){
                UserDto user = userRep.findUserById(id);
                user.setLevel(2);
                userRep.save(user);

                //如果上级的上级为
                Map<String,Object> two = relationRep.findUpById(id);
                if(!two.isEmpty()){

                    Integer id2 = Integer.parseInt(two.get("id").toString());
                    Integer level2 = Integer.parseInt(two.get("level").toString());

                    RankDto levelLog2 = rankRep.getOneByUid(id2);
                    levelLog2.setJl(levelLog2.getJl()+1);
                    rankRep.save(levelLog2);

                    //市代晋升省代
                    if(levelLog2.getJl()==3&&level2==2){

                        UserDto user2 = userRep.findUserById(id2);
                        user2.setLevel(3);
                        userRep.save(user2);

                        //找省代上级
                        Map<String,Object> three = relationRep.findUpById(id2);
                        if(!three.isEmpty()){
                            Integer id3 = Integer.parseInt(three.get("id").toString());
                            Integer level3 = Integer.parseInt(three.get("level").toString());

                            RankDto levelLog3 = rankRep.getOneByUid(id3);
                            levelLog3.setZj(levelLog3.getZj()+1);
                            rankRep.save(levelLog3);

                            //省代晋升战略合伙人
                            if(levelLog3.getZj()==6&&level3==3){
                                UserDto threeUp =  userRep.findUserById(id3);
                                threeUp.setLevel(4);
                                userRep.save(threeUp);
                            }
                        }
                    }
                }
            }
        }
    };

    /***
     * 取消用户绑定限制
     * @param ids
     * @return
     */
    @ResponseBody
    @PostMapping("/agent")
    public ResponseInfo agent(Integer ids) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        UserDto userDto = userRep.getOne(ids);
        if(userDto==null){
            return r.f("用户信息错误！");
        }
        userDto.setIsUp(1);
        userRep.save(userDto);
        return r.s();
    }

    /***
     * 设置或取消管理员
     * @param ids
     * @return
     */
    @ResponseBody
    @PostMapping("/isAdmin")
    public ResponseInfo isAdmin(Integer ids) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        UserDto userDto = userRep.getOne(ids);
        if(userDto==null){
            return r.f("用户信息错误！");
        }
        userDto.setIsAdmin(userDto.getIsAdmin()==0?1:0);
        userRep.save(userDto);
        return r.s();
    }
    /***
     * 升级
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/levelUpdate")
    public ResponseInfo levelUpdate(Integer ids){
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f();
        }
        try {
            UserDto userDto = userRep.findUserById(ids);
            if(userDto==null){
                return r.f("用户信息错误");
            }
            if(userDto.getLevel()==0){
                userDto.setLevel(1);
                userRep.save(userDto);
                //找会员上级
                Map<String,Object> one = relationRep.findUpById(userDto.getId());
                if(!one.isEmpty()) {
                    /*****
                     * 在此处理等级晋升
                     */
                    Integer id = Integer.parseInt(one.get("id").toString());
                    Integer level = Integer.parseInt(one.get("level").toString());

                    //上级增加推荐天使
                    RankDto levelLog = rankRep.getOneByUid(id);
                    levelLog.setDl(levelLog.getDl()+1);
                    rankRep.save(levelLog);

                    //如果上级为天使 且新增了三个天使 则上级升级市代
                    if(levelLog.getDl()==3&&level==1){
                        UserDto user = userRep.findUserById(id);
                        user.setLevel(2);
                        userRep.save(user);

                        //如果上级的上级为
                        Map<String,Object> two = relationRep.findUpById(id);
                        if(!two.isEmpty()){

                            Integer id2 = Integer.parseInt(two.get("id").toString());
                            Integer level2 = Integer.parseInt(two.get("level").toString());

                            RankDto levelLog2 = rankRep.getOneByUid(id2);
                            levelLog2.setJl(levelLog2.getJl()+1);
                            rankRep.save(levelLog2);

                            //市代晋升省代
                            if(levelLog2.getJl()==3&&level2==2){

                                UserDto user2 = userRep.findUserById(id2);
                                user2.setLevel(3);
                                userRep.save(user2);

                                //找省代上级
                                Map<String,Object> three = relationRep.findUpById(id2);
                                if(!three.isEmpty()){
                                    Integer id3 = Integer.parseInt(three.get("id").toString());
                                    Integer level3 = Integer.parseInt(three.get("level").toString());

                                    RankDto levelLog3 = rankRep.getOneByUid(id3);
                                    levelLog3.setZj(levelLog3.getZj()+1);
                                    rankRep.save(levelLog3);

                                    //省代晋升战略合伙人
                                    if(levelLog3.getZj()==6&&level3==3){
                                        UserDto threeUp =  userRep.findUserById(id3);
                                        threeUp.setLevel(4);
                                        userRep.save(threeUp);
                                    }
                                }
                            }
                        }
                    }
                }
            }else if(userDto.getLevel()==1){
                userDto.setLevel(2);
                userRep.save(userDto);

                //如果上级的上级为
                Map<String,Object> two = relationRep.findUpById(ids);
                if(!two.isEmpty()){

                    Integer id2 = Integer.parseInt(two.get("id").toString());
                    Integer level2 = Integer.parseInt(two.get("level").toString());

                    RankDto levelLog2 = rankRep.getOneByUid(id2);
                    levelLog2.setJl(levelLog2.getJl()+1);
                    rankRep.save(levelLog2);

                    //市代晋升省代
                    if(levelLog2.getJl()==3&&level2==2){

                        UserDto user2 = userRep.findUserById(id2);
                        user2.setLevel(3);
                        userRep.save(user2);

                        //找省代上级
                        Map<String,Object> three = relationRep.findUpById(id2);
                        if(!three.isEmpty()){
                            Integer id3 = Integer.parseInt(three.get("id").toString());
                            Integer level3 = Integer.parseInt(three.get("level").toString());

                            RankDto levelLog3 = rankRep.getOneByUid(id3);
                            levelLog3.setZj(levelLog3.getZj()+1);
                            rankRep.save(levelLog3);

                            //省代晋升战略合伙人
                            if(levelLog3.getZj()==6&&level3==3){
                                UserDto threeUp =  userRep.findUserById(id3);
                                threeUp.setLevel(4);
                                userRep.save(threeUp);
                            }
                        }
                    }
                }

            }else if(userDto.getLevel()==2){ //经理升级总监
                userDto.setLevel(3);
                userRep.save(userDto);
                //找省代上级
                Map<String,Object> three = relationRep.findUpById(ids);
                if(!three.isEmpty()){
                    Integer id3 = Integer.parseInt(three.get("id").toString());
                    Integer level3 = Integer.parseInt(three.get("level").toString());

                    RankDto levelLog3 = rankRep.getOneByUid(id3);
                    levelLog3.setZj(levelLog3.getZj()+1);
                    rankRep.save(levelLog3);

                    //省代晋升战略合伙人
                    if(levelLog3.getZj()==6&&level3==3){
                        UserDto threeUp =  userRep.findUserById(id3);
                        threeUp.setLevel(4);
                        userRep.save(threeUp);
                    }
                }
            }else if(userDto.getLevel()==3){ //经理升级总监
                userDto.setLevel(4);
                userRep.save(userDto);
            }
        }catch (Exception e){
            return r.f("操作失败，请稍后再试");
        }
        return r.f("升级成功");
    }


    /***
     * 商品列表
     * @param model
     * @return
     */
    @GetMapping("/shopGoodsList")
    public String shopGoodsList(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<Map<String, Object>> shopGoodsList = goodsRep.findAlls();
        model.addAttribute("shopGoodsList",shopGoodsList);
        return "/shop/shop_goods_list";
    }

    /**
     * 添加商品页面
     * @param model
     * @return
     */
    @GetMapping("/shopAddGoods")
    public String shopAddGoods(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        List<GoodsMenuDto> goodsMenu = goodsMenuRep.findAll();
        model.addAttribute("admin",admin);
        model.addAttribute("goodsMenu",goodsMenu);

        return "/shop/shop_goods_add";
    }

    /***
     * 添加商城分类
     * @param menuName
     * @param sort
     * @return
     */
    @ResponseBody
    @PostMapping("/addGoodsMenu")
    public ResponseInfo addGoodsMenu(String menuName, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        if(sort==null){
            sort = 0;
        }
        GoodsMenuDto goodsMenuDto = new GoodsMenuDto();
        goodsMenuDto.setMenuName(menuName);
        goodsMenuDto.setSort(sort);
        goodsMenuRep.save(goodsMenuDto);
        return r.s();
    }

    /***
     * 修改商城分类
     * @param id
     * @param menuName
     * @param sort
     * @return
     */
    @ResponseBody
    @PostMapping("/editGoodsMenu")
    public ResponseInfo editGoodsMenu(Integer id,String menuName, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        if(sort==null){
            sort = 0;
        }

        GoodsMenuDto goodsMenuDto = goodsMenuRep.getOne(id);
        if(goodsMenuDto==null){
            return r.f("获取分类信息错误，修改失败");
        }
        goodsMenuDto.setMenuName(menuName);
        goodsMenuDto.setSort(sort);
        goodsMenuRep.save(goodsMenuDto);
        return r.s();
    }

    /***
     * 删除商城分类
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delGoodsMenu")
    public ResponseInfo delGoodsMenu(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }

        List<Map<String, Object>> num = goodsRep.getGoodsMenuByMid(id);
        if(num!=null&&num.size()>0){
            return r.f("该分类下还有【"+num.size()+"】种商品，请移除或删除商品后再尝试删除！");
        }else {
            GoodsMenuDto goodsMenuDto = goodsMenuRep.getOne(id);
            if(goodsMenuDto==null){
                return r.f("获取分类信息错误，删除失败");
            }else{
                goodsMenuRep.delete(goodsMenuDto);
                return r.s();
            }
        }
    }

    @GetMapping("/shopGoodsMenu")
    public String shopGoodsMenu(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        List<GoodsMenuDto> goodsMenu = goodsMenuRep.findAll();
        model.addAttribute("admin",admin);
        model.addAttribute("goodsMenu",goodsMenu);

        return "/shop/shop_goods_menu";
    }

    /**
     * 添加商品
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/addGoods")
    public ResponseInfo addGoods(String goodsName, Double goodsPrices, String goodsSwiper, String goodsImg, String goodsContent,Integer goodsLx,Integer goodsMid,Double priceAngel,Double priceCity,Double priceProvince,Double pricePartner,Double angelPrice,Double cityPrice,Double provincePrice,Double partnerPrice,Integer goodsSort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        if(goodsLx==1){
            GoodsDto goodsDto = goodsRep.getIsDis();
            if(goodsDto!=null){
                return r.f("当前商城已经存在门槛商品，添加失败！");
            }
        }
        GoodsMenuDto goodsMenuDto = goodsMenuRep.getOne(goodsMid);
        if(goodsMenuDto==null){
            return r.f("分类信息错误，添加失败！");
        }
        GoodsDto goodsDto = new GoodsDto();
        goodsDto.setGoodsName(goodsName);
        goodsDto.setGoodsPrices(goodsPrices);
        goodsDto.setShowPrice(0d);
        goodsSwiper = goodsSwiper.replaceAll(",", "\",\"");
        goodsSwiper = "[\"" + goodsSwiper + "\"]";
        goodsDto.setGoodsSwiper(goodsSwiper);
        goodsDto.setGoodsImg(goodsImg);
        goodsDto.setGoodsContent(goodsContent);
        goodsDto.setStatus(0);
        goodsDto.setMid(goodsMid);
        goodsDto.setIsDistribution(goodsLx);//是否是分销产品 0 是 1 不是
        goodsDto.setPriceAngel(priceAngel);
        goodsDto.setPriceCity(priceCity);
        goodsDto.setPriceProvince(priceProvince);
        goodsDto.setPricePartner(pricePartner);

        goodsDto.setAngelPrice(angelPrice);
        goodsDto.setCityPrice(cityPrice);
        goodsDto.setProvincePrice(provincePrice);
        goodsDto.setPartnerPrice(partnerPrice);

        goodsDto.setSort(goodsSort);
        goodsDto = goodsRep.saveAndFlush(goodsDto);
        if(goodsDto != null && goodsDto.getId() != null && goodsDto.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }
    /**
     * 修改商品页面
     * @param model
     * @return
     */
    @GetMapping("/shopUpdGoods")
    public String shopUpdGoods(Model model, Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        GoodsDto goods = goodsRep.getOne(id);
        if(goods==null){
            return "redirect:/admin/shopGoodsList";
        }
        List<GoodsMenuDto> goodsMenu = goodsMenuRep.findAll();
        model.addAttribute("goodsMenu",goodsMenu);
        model.addAttribute("goods", goods);
        String goodsSwiper = goods.getGoodsSwiper();
        goodsSwiper = goodsSwiper.replaceAll("\"", "").replaceAll("\\[", "").replaceAll("]","");
        String goodsSwiperes[] = goodsSwiper.split(",");
        model.addAttribute("goodsSwiperes", goodsSwiperes);
        return "/shop/shop_goods_edit";
    }
    @ResponseBody
    @PostMapping("/getGoods")
    public ResponseInfo getGoods(Integer id){
        GoodsDto goodsDto = goodsRep.getOne(id);
        if(goodsDto!=null){
            return r.sd(goodsDto.getGoodsContent());
        }
        return r.f();
    }

    /**
     * 修改商品
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/updGoods")
    public ResponseInfo updGoods(Integer id, String goodsName, Double goodsPrices, String goodsSwiper, String goodsImg, String goodsContent,Integer goodsLx,Integer goodsMid,Double priceAngel,Double priceCity,Double priceProvince,Double pricePartner,Double angelPrice,Double cityPrice,Double provincePrice,Double partnerPrice,Integer goodsSort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        GoodsMenuDto goodsMenuDto = goodsMenuRep.getOne(goodsMid);
        if(goodsMenuDto==null){
            return r.f("分类信息错误，添加失败！");
        }
        GoodsDto goodsDto = new GoodsDto();
        goodsDto.setId(id);
        goodsDto.setGoodsName(goodsName);
        goodsDto.setGoodsPrices(goodsPrices);
        goodsSwiper = goodsSwiper.replaceAll(",", "\",\"");
        goodsSwiper = "[\"" + goodsSwiper + "\"]";
        goodsDto.setGoodsSwiper(goodsSwiper);
        goodsDto.setGoodsImg(goodsImg);
        goodsDto.setGoodsContent(goodsContent);
        goodsDto.setStatus(0);
        goodsDto.setMid(goodsMid);
        goodsDto.setIsDistribution(goodsLx);//是否是分销产品 0 是 1 不是
        goodsDto.setPriceAngel(priceAngel);
        goodsDto.setPriceCity(priceCity);
        goodsDto.setPriceProvince(priceProvince);
        goodsDto.setPricePartner(pricePartner);


        goodsDto.setAngelPrice(angelPrice);
        goodsDto.setCityPrice(cityPrice);
        goodsDto.setProvincePrice(provincePrice);
        goodsDto.setPartnerPrice(partnerPrice);

        goodsDto.setSort(goodsSort);
        goodsDto = goodsRep.saveAndFlush(goodsDto);
        if(goodsDto != null && goodsDto.getId() != null && goodsDto.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }
    /**
     * 商品上架、下架
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/setGoods")
    public ResponseInfo setGoods(Integer id, Integer status) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        GoodsDto goods = goodsRep.getOne(id);
        if(goods==null){
            return r.f("商品已被删除！");
        }
        goods.setStatus(status);
        goodsRep.saveAndFlush(goods);
        if(status == 1){
            return r.s("下架成功！");
        }else{
            return r.s("上架成功！");
        }
    }
    /**
     * 删除商品
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delGoods")
    public ResponseInfo delGoods(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        GoodsDto goods = goodsRep.getOne(id);
        if(goods==null){
            return r.s("删除成功！");
        }
        goodsRep.delete(goods);
        return r.s("删除成功！");
    }



    @GetMapping("/shopCzList")
    public String shopCzList(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<MoneyLogDto> logList = moneyLogRep.findLog();
        model.addAttribute("logList",logList);
        return "/shop/chongzhi_list";
    }
    @GetMapping("/shopSyList")
    public String shopSyList(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<MoneyLogDto> logList = moneyLogRep.findSyLog();
        model.addAttribute("logList",logList);
        return "/shop/shouyi_list";
    }

    @GetMapping("/articleList")
    public String articleList(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<ArticleDto> articleList = articleRep.findAll();
        model.addAttribute("articleList",articleList);
        return "/shop/article_list";
    }

    /**
     * 添加文章页面
     * @param model
     * @return
     */
    @GetMapping("/articleAdd")
    public String articleAdd(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);

        return "/shop/article_add";
    }

    /**
     * 添加文章     title + "&image=" + image + "&content=" + content,
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/addArticle")
    public ResponseInfo addArticle(String title, String image, String content) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        ArticleDto article = new ArticleDto();
        article.setAuthor("管理员");
        article.setTitle(title);
        article.setImage(image);
        article.setContent(content);
        article = articleRep.saveAndFlush(article);
        if(article != null && article.getId() != null && article.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }

    @ResponseBody
    @PostMapping("/getArticle")
    public ResponseInfo addArticle(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        ArticleDto article = articleRep.getOne(id);
        if(article != null && article.getId() != null && article.getId() > 0){
            return r.sd(article.getContent());
        }else{
            return r.f();
        }
    }

    /**
     * 修改文章页面
     * @param model
     * @return
     */
    @GetMapping("/articleUpd")
    public String articleUpd(Model model, Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        ArticleDto article = articleRep.getOne(id);
        if(article==null){
            return "redirect:/admin/articleList";
        }
        model.addAttribute("article", article);
        return "/shop/article_upd";
    }

    /**
     * 修改文章
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/updArticle")
    public ResponseInfo updArticle(Integer id, String title, String image, String content) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        ArticleDto article = articleRep.getOne(id);
        if(article==null){
            return r.f("修改失败");
        }
        article.setTitle(title);
        article.setImage(image);
        article.setContent(content);
        article = articleRep.saveAndFlush(article);

        if(article != null && article.getId() != null && article.getId() > 0){
            return r.s();
        }else{
            return r.f("修改失败");
        }
    }
    /**
     * 删除文章
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delArticle")
    public ResponseInfo delArticle(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        ArticleDto article = articleRep.getOne(id);
        if(article==null){
            return r.s("删除成功！");
        }
        articleRep.delete(article);
        return r.s("删除成功！");
    }

    /**
     * 首页排版列表
     * @param model
     * @return
     */
    @GetMapping("/uniIndex")
    public String uniIndex(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<DesignDto> designList = designRep.index();
        model.addAttribute("designList",designList);
        return "/shop/uni_index";
    }

    /**
     * 添加首页排版页面
     * @param model
     * @return
     */
    @GetMapping("/indexAdd")
    public String indexAdd(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);

        return "/shop/index_add";
    }

    /**
     * 添加首页排版
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/addIndex")
    public ResponseInfo addIndex(Integer type, Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        DesignDto design = new DesignDto();
        design.setType(type);
        design.setGid(gid);
        design.setImg(img);
        design.setSort(sort);
        design.setSite(0);
        design = designRep.saveAndFlush(design);
        if(design != null && design.getId() != null && design.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }
    /**
     * 修改首页排版页面
     * @param model
     * @return
     */
    @GetMapping("/indexUpd")
    public String indexUpd(Model model, Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        DesignDto design = designRep.getOne(id);
        if(design==null){
            return "redirect:/admin/uniIndex";
        }
        model.addAttribute("design", design);
        return "/shop/index_upd";
    }

    /**
     * 修改首页排版
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/updIndex")
    public ResponseInfo updIndex(Integer id, Integer type, Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        DesignDto design = designRep.getOne(id);
        if(design==null){
            return r.f("修改失败");
        }
        design.setId(id);
        design.setType(type);
        design.setGid(gid);
        design.setImg(img);
        design.setSort(sort);
        design = designRep.saveAndFlush(design);

        if(design != null && design.getId() != null && design.getId() > 0){
            return r.s();
        }else{
            return r.f("修改失败");
        }
    }
    /**
     * 删除首页排版
     * @param id
     * @return
     */
    @ResponseBody
    @PostMapping("/delIndex")
    public ResponseInfo delIndex(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        DesignDto designDto = designRep.getOne(id);
        if(designDto!=null){
            designRep.delete(designDto);
            return r.s("删除成功！");
        }
        return r.s("删除成功！");
    }

    /***
     * 微笑计划排版
     * @param model
     * @return
     */
    @GetMapping("/uniHome")
    public String uniHome(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<DesignDto> designList = designRep.home();
        List<ArticleDto> articleList = articleRep.findAll();
        model.addAttribute("designList",designList);
        model.addAttribute("articleList",articleList);
        return "/shop/uni_home";
    }

    @GetMapping("/uniSwiper")
    public String uniSwiper(Model model) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return "redirect:/admin/login";
        }
        if(admin.getIsEditPwd()==1){
            return "redirect:/admin/userinfo";
        }
        model.addAttribute("admin",admin);
        List<SwiperDto> swiperList = swiperRep.findAll();
        List<ArticleDto> articleList = articleRep.findAll();
        model.addAttribute("articleList",articleList);
        model.addAttribute("swiperList",swiperList);
        return "/shop/uni_swiper";
    }
    @ResponseBody
    @PostMapping("/delSwiper")
    public ResponseInfo delSwiper(Integer id) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        SwiperDto swiperDto = swiperRep.getOne(id);
        if(swiperDto!=null){
            swiperRep.delete(swiperDto);
            return r.s("删除成功！");
        }
        return r.s("删除成功！");
    }
    @ResponseBody
    @PostMapping("/updSwiper")
    public ResponseInfo updSwiper(Integer id, Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        SwiperDto swiperDto = swiperRep.getOne(id);
        if(swiperDto==null){
            return r.f("修改失败");
        }
        swiperDto.setImage(img);
        swiperDto.setUrl("/pages/article/index?id="+gid);
        swiperDto.setSort(sort);
        swiperDto = swiperRep.saveAndFlush(swiperDto);
        if(swiperDto != null && swiperDto.getId() != null && swiperDto.getId() > 0){
            return r.s();
        }else{
            return r.f("修改失败");
        }
    }

    @ResponseBody
    @PostMapping("/addSwiper")
    public ResponseInfo addSwiper( Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
       SwiperDto swiperDto = new SwiperDto();
        swiperDto.setImage(img);
        swiperDto.setUrl("/pages/article/index?id="+gid);
        swiperDto.setSort(sort);
        swiperDto.setStatus(0);
        swiperDto.setJump("navigateTo");
        swiperDto.setType(0);
        swiperDto.setTitle("新增");
        swiperDto = swiperRep.saveAndFlush(swiperDto);
        if(swiperDto != null && swiperDto.getId() != null && swiperDto.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }

    /**
     * 添加微笑计划排版
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/addHome")
    public ResponseInfo addIndex( Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        DesignDto design = new DesignDto();
        design.setType(1);
        design.setGid(gid);
        design.setImg(img);
        design.setSort(sort);
        design.setSite(1);
        design = designRep.saveAndFlush(design);
        if(design != null && design.getId() != null && design.getId() > 0){
            return r.s();
        }else{
            return r.f("插入失败");
        }
    }
    /**
     * 修改首页排版
     * @param model
     * @return
     */
    @ResponseBody
    @PostMapping("/updHome")
    public ResponseInfo updHome(Integer id, Integer gid, String img, Integer sort) {
        HttpSession session = req.getSession();
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f("请登录");
        }
        if(admin.getIsEditPwd()==1){
            return r.f("请登录");
        }
        DesignDto design = designRep.getOne(id);
        if(design==null){
            return r.f("修改失败");
        }
        design.setType(1);
        design.setGid(gid);
        design.setImg(img);
        design.setSort(sort);
        design.setSite(1);
        design = designRep.saveAndFlush(design);

        if(design != null && design.getId() != null && design.getId() > 0){
            return r.s();
        }else{
            return r.f("修改失败");
        }
    }


    /***
     * 发货
     * @param id
     * @param kuaidi
     * @param danhao
     * @return
     */
    @ResponseBody
    @PostMapping("fahuo")
    public ResponseInfo index(String id, String kuaidi,String danhao) {
        AccountDto admin = getAccount();
        if(admin==null){
            return r.f();
        }
        OrdersDto ordersDto = ordersRep.findOrderById(id);
        if(ordersDto!=null){
            ordersDto.setCourierName(kuaidi);
            ordersDto.setCourierNumber(danhao);
            ordersDto.setState(1);
            ordersRep.save(ordersDto);




            UserDto userDto = userRep.getOne(ordersDto.getUserId());

            if(userDto.getOpenid()!=null){
                JSONObject data = new JSONObject();
                JSONObject name1 = new JSONObject();
                name1.put("value",ordersDto.getId());
                data.put("character_string1",name1);

                JSONObject thing3 = new JSONObject();
                thing3.put("value","已发货");
                data.put("phrase2",thing3);

                JSONObject time4 = new JSONObject();
                time4.put("value",kuaidi);
                data.put("name3",time4);


                JSONObject date4 = new JSONObject();
                date4.put("value",danhao);
                data.put("character_string4",date4);

                JSONObject thing6 = new JSONObject();
                thing6.put("value","订单物流信息请在官网查询");
                data.put("thing5",thing6);
                WxTempMsg.sendMsg(userDto.getOpenid(),"/pages/me/orders/index?index=0",data,"pjqTDJPO4x-3BnyRgnh3qOahzgb2qPAbSYNKvAHV5jk");
            }





            return r.s();
        }
        return r.f("请稍后再试");
    }

//    @ResponseBody
//    @GetMapping("/dataChars")
//    public ResponseInfo dataChars(){
//
//        AccountDto admin = getAccount();
//        if(admin==null){
//            return r.f();
//        }
//        if(admin.getType()==0||admin.getType()==1){
//            List<GroupDto> groupDtoList = groupRepository.findAll();
//            JSONArray gift = new JSONArray();
//            JSONArray uses = new JSONArray();
//            JSONArray sur = new JSONArray();
//            JSONArray groupName = new JSONArray();
//            for(GroupDto groupDto:groupDtoList){
//                gift.add(groupDto.getGift());
//                uses.add(groupDto.getUses());
//                sur.add(groupDto.getSur());
//                groupName.add(groupDto.getGroupName());
//            }
//            JSONObject data = new JSONObject();
//            data.put("gift",gift);
//            data.put("uses",uses);
//            data.put("sur",sur);
//            data.put("groupName",groupName);
//            return r.s(data.toString());
//        }else{
//            List<AccountDto> accountDtoList = accountRepository.findGroupAll(admin.getGroupId());
//            JSONArray gift = new JSONArray();
//            JSONArray uses = new JSONArray();
//            JSONArray sur = new JSONArray();
//            JSONArray groupName = new JSONArray();
//            for(AccountDto AccountDto:accountDtoList){
//                gift.add(AccountDto.getGift());
//                uses.add(AccountDto.getUses());
//                sur.add(AccountDto.getSur());
//                groupName.add(AccountDto.getUsername());
//            }
//            JSONObject data = new JSONObject();
//            data.put("gift",gift);
//            data.put("uses",uses);
//            data.put("sur",sur);
//            data.put("groupName",groupName);
//            return r.s(data.toString());
//        }
//    }
    /***
     * 退出登录
     * @return
     */
    @GetMapping("/out")
    public String out() {
        HttpSession session =  req.getSession();
        session.removeAttribute("tishi");
        session.removeAttribute("LOGIN");
        return "/admin/auth_login";
    }

    /***
     * 登录页面
     * @param model
     * @return
     */
    @GetMapping("login")
    public String login(Model model) {
        return "/admin/auth_login";
    }

    /***
     * 后台登录
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @PostMapping("login")
    public ResponseInfo index(String username, String password) {
        HttpSession session =  req.getSession();
        if(username.isEmpty()||password.isEmpty()){
            return r.f("请检查账号密码");
        }
        AccountDto admin = accountRepository.findAdmin(username);
        if(admin==null){
            return r.f("账号错误");
        }else {
            if(!admin.getPassword().equals(password)){
                return r.f("密码错误");
            }
            if(session!=null){
                session.setAttribute("LOGIN",admin);
                adminusername = admin.getUsername();
                admintype = admin.getType();
                adminacccount = admin.getAccount();
                return r.s();
            }
        }
        return r.f("请稍后再试！");
    }

    /***
     * 求百分比
     * @param i 总数
     * @param j  除数
     * @return
     */
    public String getBaiFen(Integer i,Integer j ){
        Integer chapterCount = i;//总课数
        Integer learnCount = j;//所上课数
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float)  learnCount/ (float)chapterCount* 100);//所占百分比
        return result;
    }

}
